package com.galaxy.payment.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.galaxy.common.core.utils.StringUtils;
import com.galaxy.common.mybatis.core.page.PageQuery;
import com.galaxy.common.mybatis.core.page.TableDataInfo;
import com.galaxy.payment.domain.AccountFlow;
import com.galaxy.payment.domain.bo.AccountFlowBo;
import com.galaxy.payment.domain.convert.AccountFlowConvert;
import com.galaxy.payment.domain.vo.AccountFlowVo;
import com.galaxy.payment.mapper.AccountFlowMapper;
import com.galaxy.payment.service.IAccountFlowService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * 资金流水记录Service业务层处理
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class AccountFlowServiceImpl implements IAccountFlowService {

    private final AccountFlowMapper baseMapper;

    /**
     * 查询账户流水列表
     */
    @DS("slave")
    @Override
    public TableDataInfo<AccountFlowVo> queryPageList(AccountFlowBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AccountFlow> lqw = buildQueryWrapper(bo);
        IPage<AccountFlowVo> page = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(page);
    }

    /**
     * 查询账户流水列表
     */
    @DS("slave")
    @Override
    public List<AccountFlowVo> queryList(AccountFlowBo bo) {
        LambdaQueryWrapper<AccountFlow> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 查询账户流水
     */
    @DS("slave")
    @Override
    public AccountFlowVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 新增账户流水
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(AccountFlowBo bo) {
        AccountFlow add = AccountFlowConvert.INSTANCE.boToEntity(bo);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改账户流水
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(AccountFlowBo bo) {
        AccountFlow update = AccountFlowConvert.INSTANCE.boToEntity(bo);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 校验并批量删除账户流水
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // TODO: 做一些业务上的校验,判断是否允许删除
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 处理充值回调
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean handleRechargeCallback(String orderNo, String tradeNo, Integer status) {
        AccountFlow accountFlow = baseMapper.selectOne(Wrappers.<AccountFlow>lambdaQuery()
            .eq(AccountFlow::getOrderNo, orderNo));
        if (accountFlow == null) {
            return false;
        }
        return baseMapper.updateById(accountFlow) > 0;
    }

    /**
     * 取消充值
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean cancelRecharge(String orderNo) {
        AccountFlow accountFlow = baseMapper.selectOne(Wrappers.<AccountFlow>lambdaQuery()
            .eq(AccountFlow::getOrderNo, orderNo));
        if (accountFlow == null) {
            return false;
        }
        return baseMapper.updateById(accountFlow) > 0;
    }

    /**
     * 构建查询条件
     */
    private LambdaQueryWrapper<AccountFlow> buildQueryWrapper(AccountFlowBo bo) {
        LambdaQueryWrapper<AccountFlow> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getUserId() != null, AccountFlow::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getOrderNo()), AccountFlow::getOrderNo, bo.getOrderNo());
        lqw.eq(bo.getFlowType() != null, AccountFlow::getFlowType, bo.getFlowType());
        lqw.orderByDesc(AccountFlow::getCreateTime);
        return lqw;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(AccountFlow entity) {
        // TODO: 做一些实体的数据校验,如唯一约束
    }

    @Override
    public List<AccountFlowVo> queryByUserId(Long userId) {
        LambdaQueryWrapper<AccountFlow> lqw = Wrappers.lambdaQuery();
        lqw.eq(AccountFlow::getUserId, userId);
        lqw.orderByDesc(AccountFlow::getCreateTime);
        return baseMapper.selectVoList(lqw);
    }

    @Override
    public AccountFlowVo queryByOrderNo(String orderNo) {
        return baseMapper.selectVoOne(Wrappers.<AccountFlow>lambdaQuery()
            .eq(AccountFlow::getOrderNo, orderNo));
    }

    @Override
    public AccountFlowVo getAccountFlow(Long userId) {
        return baseMapper.selectVoOne(Wrappers.<AccountFlow>lambdaQuery()
            .eq(AccountFlow::getUserId, userId)
            .orderByDesc(AccountFlow::getCreateTime)
            .last("LIMIT 1"));
    }


    /**
     * 生成充值单号
     */
    private String generateRechargeNo() {
        return "RECH" + System.currentTimeMillis() + String.format("%04d", (int)(Math.random() * 10000));
    }
}
